<?php


namespace Modules\File\Actions;


use App\Traits\AsAction;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Modules\File\Models\Attachment;

class ImgUpload
{
    use AsAction;


    /**
     * @param UploadedFile $file
     * @return array
     * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
     */
    public function handle(UploadedFile $file)
    {
        $md5_key = md5($file->get());
        $disk = Storage::disk('oss');

        if(!$exist = Attachment::where('uuid', $md5_key)->first()) {
            $data = [
                'uuid' => $md5_key,
                'is_remote' => true,
                'is_sound' => false,
                'is_approved' => true,
                'attachment' => $file->hashName(),
                'file_path' => config('file.path') . date('Y/m/d') . '/',
                'file_name' => $file->getClientOriginalName(),
                'file_size' => $file->getSize(),
                'file_type' => $file->getMimeType()
            ];

            $disk->put($data['file_path'], $file);

            $file->storeAs($data['file_path'], $data['attachment'], 'oss');
            $exist = Attachment::create($data);
        }

        return [
            'file_id' => $exist->uuid,
            'file_name' => $exist->file_name,
            'file_size' => $exist->file_size,
            'url' => $disk->getUrl($exist['file_path'] . $exist['attachment'])
        ];

    }


}
